<template>
    <div class="content-wrapper" v-loading.fullscreen.lock="fullscreenLoading">
        <el-row class="content-row">
            <el-form ref="addForm" :model="addForm" :rules="addRules" label-width="140px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="本期秒杀活动时间" prop="time">
                            <el-date-picker
                                    v-model="addForm.time"
                                    type="datetimerange"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    style="width:380px"
                                    :default-time="['00:00:00', '23:59:59']">
                            </el-date-picker>
                        </el-form-item>

                        <div style="width:100%;text-align: right;">
                            <el-button-group style="float: right">
                                <el-button type="text" size="small" icon="el-icon-plus" @click="onAddExternalRow">
                                    新增秒杀商品
                                </el-button>
                            </el-button-group>
                        </div>
                        <el-table
                                ref="externalTable"
                                :data="externalData"
                                stripe
                                border
                                style="width: 100%;"
                                height="900"
                                :cell-style="cellStyleAlignCenter"
                        >
                            <el-table-column type="index" width="50" label="序号"/>
                            <el-table-column prop="goodsId" label="商品ID">
                                <template slot-scope="{row}">
                                    <span>{{row.goodsId}}</span>
                                </template>
                            </el-table-column>

                            <el-table-column prop="goodsName" label="商品名称">
                                <template slot-scope="{row}">
                                    <span>{{row.goodsName}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="headImg" label="商品头图">
                                <template slot-scope="{row}">
                                    <img v-if="row.headImg != null" :src="row.headImg" class="image" width="168px"
                                         height="168px"/>
                                </template>
                            </el-table-column>

                            <el-table-column prop="goodsSpec" label="规格">
                                <template slot-scope="{row}">
                                    <span>{{row.goodsSpec}}</span>
                                </template>
                            </el-table-column>

                            <el-table-column prop="integralNum" label="消耗积分">
                                <template slot-scope="{row}">
                                    <span>{{row.integralNum}}</span>
                                </template>
                            </el-table-column>

                            <el-table-column prop="marketPrice" label="市场价格">
                                <template slot-scope="{row}">
                                    <span>{{row.marketPrice}}</span>
                                </template>
                            </el-table-column>

                            <el-table-column prop="num" label="本期数量">
                                <template slot-scope="{row}">
                                    <el-input type="text" maxlength="10" v-model="row.num"/>
                                    <span>当前库存:{{row.inventoryNum}}</span>

                                </template>
                            </el-table-column>

                            <el-table-column prop="maxNum" label="个人最大秒杀数量">
                                <template slot-scope="{row}">
                                    <el-input type="text" maxlength="10" v-model="row.maxNum"/>

                                </template>
                            </el-table-column>


                            <!-- <el-table-column prop="type" width="100" label="类型" >
                              <template slot-scope="{row}">
                                {{row.type === 2 ? "字符串":row.type === 1?'数字': row.type === 3?'时间':'其它'}}
                              </template>
                            </el-table-column> -->
                            <el-table-column width="200" label="操作">

                                <template slot-scope="scope">
                                    <!--                                        <el-button type="text" size="small" icon="el-icon-delete" @click="onDelExternalRow(scope.row,scope.$index)">新增</el-button>-->
                                    <el-button type="text" size="small" icon="el-icon-delete"
                                               @click="selectGoods(scope.row,scope.$index)">选择商品
                                    </el-button>
                                    <!--                                        <el-button type="text" size="small" icon="el-icon-delete" @click="onDelExternalRow(scope.row,scope.$index)">更改数量</el-button>-->
                                    <el-button type="text" size="small" icon="el-icon-delete"
                                               @click="onDelExternalRow(scope.row,scope.$index)">删除
                                    </el-button>
                                </template>
                            </el-table-column>

                        </el-table>

                    </el-col>
                </el-row>


            </el-form>
        </el-row>

        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="closeTab">取 消</el-button>
            <el-button type="primary" @click="saveForm('addForm',0)">保存</el-button>
            <el-button type="primary" @click="saveForm('addForm',1)">发布</el-button>
        </div>


        <!-- 新增弹出框 -->
        <el-dialog title="选择商品" :visible.sync="selectGoodsVisible" width="60%">
            <el-row class="handle-box">

                <el-input v-model="query.goodsName" placeholder="商品名称" style="width: 200px"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </el-row>

            <el-row>

                <el-table
                        :data="tableData"
                        border
                        class="table"
                        height="300px"
                        ref="multipleTable"
                        @row-click="rowClick"
                        header-cell-class-name="table-header"
                        highlight-current-row
                        @current-change="rowClick"
                >

                    <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
                    <el-table-column prop="id" label="商品编号" align="center"></el-table-column>
                    <el-table-column prop="goodsName" width="200" align="center" label="商品名称"
                                     show-overflow-tooltip/>
                    <el-table-column prop="goodsSpec" align="center" label="规格数量" show-overflow-tooltip/>
                    <el-table-column prop="marketPrice" align="center" label="市面价格" show-overflow-tooltip/>
                    <el-table-column prop="goodsSpecUnit" align="center" label="规格单位" show-overflow-tooltip/>
                    <el-table-column prop="totelNum" align="center" label="总数量" show-overflow-tooltip>
                        <template slot-scope="scope">
                            {{scope.row.inventoryNum + scope.row.salesNum }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="inventoryNum" align="center" label="剩余数量" show-overflow-tooltip/>
                    <el-table-column prop="salesNum" align="center" label="已兑换数量" show-overflow-tooltip/>
                </el-table>

            </el-row>

            <span slot="footer" class="dialog-footer2">
                        <el-button @click="updateClose">取 消</el-button>
                        <el-button type="primary" @click="setGoods('addForm')">确 定</el-button>
                        </span>
        </el-dialog>

    </div>
</template>

<script>

    // import CityTree from './CityTree'
    // import titleTip from '../../../common/titleTip.vue'
    import {add} from '../../../../api/mall/seckill'
    import {getReleaseMallGoodsDetails} from '../../../../api/mall/goodsDetail'


    export default {
        name: 'goodsDetailAdd',

        data() {
            var checkActivityTime = (rule, value, callback) => {
                let applyTime = this.addForm.applyTime;
                let activityTime = value;

                if (applyTime.length > 0 && activityTime.length > 0) {

                    let activityBeginTime = activityTime[0].getTime();
                    let activityEndTime = activityTime[1].getTime();

                    let applyBeginTime = applyTime[0].getTime();
                    let applyEndTime = applyTime[1].getTime();

                    console.log(activityBeginTime, activityEndTime, applyBeginTime, applyEndTime)

                    if (activityEndTime < applyEndTime) {
                        return callback(new Error("活动结束时间不得早于报名结束时间"));
                    } else if (activityBeginTime < applyBeginTime) {
                        return callback(new Error("报名开始时间不得迟于活动开始时间"));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }

            };
            var checkApplyTime = (rule, value, callback) => {
                let applyTime = value;
                let activityTime = this.addForm.time;
                if (applyTime.length > 0 && activityTime.length > 0) {

                    let activityBeginTime = activityTime[0].getTime();
                    let activityEndTime = activityTime[1].getTime();

                    let applyBeginTime = applyTime[0].getTime();
                    let applyEndTime = applyTime[1].getTime();

                    console.log(activityBeginTime, activityEndTime, applyBeginTime, applyEndTime)


                    if (activityEndTime < applyEndTime) {
                        return callback(new Error("活动结束时间不得早于报名结束时间"));
                    } else if (activityBeginTime < applyBeginTime) {
                        return callback(new Error("报名开始时间不得迟于活动开始时间"));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }

            };
            return {
                multipleSelection: [],
                query: {
                    goodsName: ''
                },
                selectGoodsVisible: false,
                activityTypeOptions: [{
                    value: '1',
                    label: '广告图文类'
                }, {
                    value: '2',
                    label: '现场活动类'
                }, {
                    value: '3',
                    label: '线上报名类'
                }],
                isAdvertise: true,//广告图片
                isOnline: false,//线上活动
                isOffline: false,//线下活动

                externalData: [],
                tableData: [],
                picList: [],
                detailPicList: [],
                advertisePicList: [],

                editIndex: '',
                editRow: {},
                spaces: [],
                uploadImgNum: 0,
                uploadDetailImgNum: 0,
                uploadAdvertiseImgNum: 0,

                dialogImageUrlImg: '',
                dialogVisibleImg: false,


                limit: 1,
                advertiseLimit: 5,
                detailPicLimit: 5,

                openDialog: false,
                viewdialog: false,
                fullscreenLoading: false,

                apply: true,

                detailsImg: [],
                carouselImgList: [],
                currentRow: {},
                currentIndex: 0,
                uploadUrl: 'https://lht.ah-zk.com/qjt/fs/file/upload',
                origin: 'https://lht.ah-zk.com/qjt/fs/origin',
                imageStyle: [
                    // {
                    //     code: "1",
                    //     name: "单图",
                    //     url: require("../../../../assets/img/01.png")
                    // }, {
                    //     code: "2",
                    //     name: "双图",
                    //     url: require("../../../../assets/img/02.png")
                    // }, {
                    //     code: "3",
                    //     name: "三图",
                    //     url: require("../../../../assets/img/03.png")
                    // }, {
                    //     code: "4",
                    //     name: "四图",
                    //     url: require("../../../../assets/img/04.png")
                    // }
                ],
                addForm: {
                    time: ''
                },
                addRules: {
                    time: [
                        {required: true, message: '选择时间', trigger: ['blur', 'change']}
                    ]
                }
            };
        },
        created() {
            // this.changeStyle();
            // this.getMoreSpace();
            this.getData();
        },
        components: {
            // subBannerDeatil,
            //CityTree,
            //titleTip
        },
        methods: {

            onAddExternalRow() {
                // if(this.externalData.length>2){
                //     this.$message({
                //         message: '不能添加3个商品以上！',
                //         type: 'warning'
                //     });
                //     return;
                // }
                let external = {}
                this.externalData.push(external)
            },
            //关闭tab
            closeTab() {
                this.closeTagByName('seckillAdd');
            },
            //跳转到选择项目弹出框
            viewCity() {
                this.viewdialog = true;
            },
            //选择项目后的回调
            viewinf(e) {
                this.viewdialog = false;
                this.addForm.cityList = e;
                let cityNames = "";
                if (e.length != 0) {
                    for (let i = 0; i < e.length; i++) {
                        if (i != 0) {
                            cityNames += ",";
                        }
                        cityNames += e[i].cityName;
                    }
                }
                this.addForm.cityName = cityNames;
                this.addForm.scope = '2';
            },
            updateClose() {
                this.selectGoodsVisible = false;

            },
            /**
             * 获取列表
             */
            getData() {
                getReleaseMallGoodsDetails(this.query).then(res => {
                    console.log(res);
                    this.tableData = res.data.records;
                    this.pageTotal = res.data.total || 50;
                });
            },
            //图片上传删除图片
            handleRemoveImg(file, fileList) {
                this.uploadImgNum = 0;
                this.addForm.headImg = null;
            },
            //图片放大方法
            handlePictureCardPreviewImg(file) {
                this.dialogImageUrlImg = file.url;
                this.dialogVisibleImg = true;
            },
            //图片上传成功回调
            successUploadImg(response, file, fileList) {
                let f = response.files[0];
                this.addForm.headImg = f.fingerprint;
                this.uploadImgNum = 1;
            },

            //图片上传删除图片
            handleRemoveDetailImg(file, fileList) {
                var deleteFileName = file.response.files[0].fingerprint;
                for (var i = 0; i < this.detailPicList.length; i++) {
                    var fileName = this.detailPicList[i];
                    if (fileName == deleteFileName) {
                        this.detailPicList.splice(i, 1);
                        break;
                    }
                }
                this.uploadDetailImgNum--;
                this.addForm.activityAdvertiseImg = null;
            },
            //图片放大方法
            // handlePictureCardPreviewDetailImg(file) {
            //     this.dialogImageUrlImg = file.url;
            //     this.dialogVisibleImg = true;
            // },
            //图片上传成功回调
            successUploadDetailImg(response, file, fileList) {
                let f = response.files[0];
                //this.addForm.activityAdvertiseImg = f.fingerprint;
                // this.detailPicList.push()
                this.detailsImg.push(f.fingerprint);
                this.uploadDetailImgNum++;

            },

            //图片上传成功回调
            successUploadAdvertiseImg(response, file, fileList) {
                let f = response.files[0];
                //this.addForm.activityAdvertiseImg = f.fingerprint;
                this.carouselImgList.push(f.fingerprint)
                this.uploadAdvertiseImgNum++;

                console.log(this.carouselImgList);
            },

            //图片上传删除图片
            handleRemoveAdvertiseImg(file, fileList) {
                var deleteFileName = file.response.files[0].fingerprint;
                for (var i = 0; i < this.carouselImgList.length; i++) {
                    var fileName = this.carouselImgList[i];
                    if (fileName == deleteFileName) {
                        this.carouselImgList.splice(i, 1);
                        break;
                    }
                }
                this.uploadAdvertiseImgNum--;
                this.addForm.activityAdvertiseImg = null;

            },
            //文件上传时做文件大小判断
            beforeUpload(file) {
                const isLt2M = file.size / 1024 / 1024 < 2
                if (!isLt2M) {
                    this.$message({
                        message: '上传文件大小不能超过 200KB!',
                        type: 'warning'
                    });
                }
                return isLt2M;
            },
            selectGoods(row, index) {
                //
                // let json = {
                //     id: 100,
                //     goodsName:'asdf',
                //     num:100
                // }
                // this.externalData[] = json
                this.currentIndex = index;
                // console.log(this.externalData);
                this.selectGoodsVisible = true;
            }, setGoods() {
                if(this.currentRow.id == null){
                    this.$message({
                        message: '请选择一个商品',
                        type: 'error'
                    });
                    return;
                }
                this.currentRow.headImg = this.origin + "/" + this.currentRow.headImg;
                this.currentRow.goodsId = this.currentRow.id;

                delete this.currentRow["id"];
                this.$set(this.externalData, this.currentIndex, this.currentRow);
                this.selectGoodsVisible = false;

                this.currentIndex = -1;
                this.currentRow = {};
            },
            onDelExternalRow(row, index) {
                this.externalData.splice(index, 1)
            },
            //提交保存
            saveForm(formName, status) {
                let valid1 = false;
                let valid2 = false;

                let valid3 = false;


                this.addForm.externals = this.externalData.filter(item => {

                    if(!item.goodsId){
                        valid1 = true;
                    }
                    if(!item.num ){
                        valid2 = true;

                    }
                    if(!item.maxNum ){
                        valid3 = true;

                    }
                    console.log("数量",item.num);
                    return item
                });

                if(valid1){
                    this.$message({
                        message: '请所有行都选择商品',
                        type: 'error'
                    });
                    return
                }

                if(valid2){
                    this.$message({
                        message: '请填入秒杀数量',
                        type: 'error'
                    });
                    return;
                }

                if(valid3){
                    this.$message({
                        message: '请填入个人最大秒杀数量',
                        type: 'error'
                    });
                    return;
                }

                if(this.addForm.externals.length==0){
                    this.$message({
                        message: '至少添加一个商品',
                        type: 'error'
                    });
                    return;
                }


                this.addForm.startTime = new Date(this.addForm.time[0]).getTime();
                this.addForm.endTime = new Date(this.addForm.time[1]).getTime();

                this.addForm.status = status;

                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.fullscreenLoading = true;

                        add(this.addForm).then(res => {
                            if (res.code == '0') {
                                this.fullscreenLoading = false;
                                this.$message({
                                    message: '新增成功',
                                    type: 'success'
                                });
                                this.resetForm('addForm');
                                this.closeTagByName('seckillAdd');
                                this.$router.push('/mall/seckill/list');
                            } else {
                                this.fullscreenLoading = false;
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                            }
                        });
                    } else {
                        return false;
                    }
                })

            },// 触发搜索按钮
            handleSearch() {
                this.$set(this.query, 'pageNo', 1);
                this.getData();
            },

            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            }, rowClick(val) {
                this.currentRow = val;
            },

            // 分页导航
            handlePageChange(val) {
                this.$set(this.query, 'pageNo', val);
                this.getData();
            },
            //分页器
            handleSizeChange(val) {
                this.$set(this.query, 'pageSize', val);
                this.getData();
            },
        }
    };
</script>

<style scoped>

    .content-wrapper {
        height: 100%;
        overflow-y: scroll;
    }

    .content-row {
        height: 94%;
        overflow-y: scroll;
    }

    .imageFloatLeft {
        width: 40%;
        float: left;
        height: 140px;
        margin-right: 2%;
    }

    .dialog-footer {
        text-align: center;
    }
</style>
